package com.tnovoselec.android.mojevijesti.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nth.android.image.ImageDownloader;
import com.tnovoselec.android.mojevijesti.R;
import com.tnovoselec.android.mojevijesti.dto.NewsItemDto;

public class NewsAdapter extends BaseAdapter {

	private List<NewsItemDto> items;
	private LayoutInflater inflater;
	private ImageDownloader imageDownloader;

	public NewsAdapter(Context mContext, List<NewsItemDto> items) {
		this.items = items;
		inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageDownloader = ImageDownloader.getInstance();
	}

	@Override
	public int getCount() {
		return items!=null? items.size():0;
	}

	@Override
	public Object getItem(int arg0) {
		return items.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertview, ViewGroup parent) {
		ViewHolder holder;
		NewsItemDto item = items.get(position);
		if (convertview == null) {
			convertview = inflater.inflate(R.layout.news_list_item, parent, false);
			holder = new ViewHolder();
			holder.image = (ImageView) convertview.findViewById(R.id.news_list_item_image);
			holder.title = (TextView) convertview.findViewById(R.id.news_list_item_title);
			convertview.setTag(holder);
		}
		holder = (ViewHolder) convertview.getTag();
		holder.title.setText(item.getTitle());
		String imageUrl = item.getImages().size() != 0 ? item.getImages().get(0) : null;
		if (imageUrl != null) {
			imageDownloader.download(imageUrl, holder.image);
			holder.image.setVisibility(View.VISIBLE);
		} else {
			holder.image.setVisibility(View.GONE);
		}
		return convertview;
	}

	class ViewHolder {
		ImageView image;
		TextView title;
	}
}
